import { defineStore } from 'pinia';
import {
  getPermissionList,
  addPermission,
  editPermission,
  deletePermission,
  enablePermission,
  disablePermission
} from '@/api/permission';
import { ElMessage } from 'element-plus';

export const usePermissionStore = defineStore('permissionStore', {
  state: () => ({
    permissions: [],
    total: 0,
    page: 1,
    pageSize: 10,
    loading: false,
    currentPermission: null,
    dialogVisible: false,
    isEdit: false
  }),

  getters: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    hasPrevPage() {
      return this.page > 1;
    },
    hasNextPage() {
      return this.page < this.totalPages;
    },
  },

  actions: {
    // 设置当前页码
    setPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.page = page;
        this.fetchPermissions();
      }
    },

    // 设置每页条数
    setPageSize(pageSize) {
      this.pageSize = pageSize;
      this.page = 1;
      this.fetchPermissions();
    },

    // 获取权限列表
    async fetchPermissions() {
      this.loading = true;
      try {
        const response = await getPermissionList({
          pageIndex: this.page,
          pageSize: this.pageSize,
        });

        if (response && response.code === 200 && response.data) {
          this.permissions = response.data.items || [];
          this.total = response.data.totalCount || 0;
        } else {
          this.permissions = [];
          this.total = 0;
          ElMessage.error('获取权限列表失败: 无效的响应格式');
        }
      } catch (error) {
        ElMessage.error('获取权限列表失败: ' + (error.message || '未知错误'));
        console.error('Failed to fetch permissions list:', error);
      } finally {
        this.loading = false;
      }
    },

    // 新增权限
    async addPermission(permissionData) {
      this.loading = true;
      try {
        const response = await addPermission(permissionData);
        if (response && response.code === 200) {
          ElMessage.success(response.data);
          this.fetchPermissions();
          return true;
        } else {
          ElMessage.error(response.message);
          return false;
        }
      } catch (error) {
        ElMessage.error('添加权限失败: ' + (error.message || '未知错误'));
        console.error('Failed to add permission:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 编辑权限
    async editPermission(permissionId, permissionData) {
      this.loading = true;
      try {
        const response = await editPermission(permissionId, permissionData);
        if (response && response.code === 200) {
          ElMessage.success('权限更新成功');
          this.fetchPermissions();
          return true;
        } else {
          ElMessage.error('更新权限失败: ' + (response.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('更新权限失败: ' + (error.message || '未知错误'));
        console.error('Failed to edit permission:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 删除权限
    async deletePermission(permissionId) {
      this.loading = true;
      try {
        const response = await deletePermission(permissionId);
        if (response && response.code === 200) {
          ElMessage.success('权限删除成功');
          this.fetchPermissions();
          return true;
        } else {
          ElMessage.error('删除权限失败: ' + (response.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('删除权限失败: ' + (error.message || '未知错误'));
        console.error('Failed to delete permission:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 启用权限
    async enablePermission(permissionId) {
      this.loading = true;
      try {
        const response = await enablePermission(permissionId);
        if (response && response.code === 200) {
          ElMessage.success('权限启用成功');
          this.fetchPermissions();
          return true;
        } else {
          ElMessage.error('启用权限失败: ' + (response.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('启用权限失败: ' + (error.message || '未知错误'));
        console.error('Failed to enable permission:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 禁用权限
    async disablePermission(permissionId) {
      this.loading = true;
      try {
        const response = await disablePermission(permissionId);
        if (response && response.code === 200) {
          ElMessage.success('权限禁用成功');
          this.fetchPermissions();
          return true;
        } else {
          ElMessage.error('禁用权限失败: ' + (response.message || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('禁用权限失败: ' + (error.message || '未知错误'));
        console.error('Failed to disable permission:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 切换权限状态
    async togglePermissionStatus(permission) {
      try {
        if (permission.isActive) {
          await this.disablePermission(permission.id);
        } else {
          await this.enablePermission(permission.id);
        }
      } catch (error) {
        console.error('Failed to toggle permission status:', error);
      }
    },

    // 打开编辑对话框
    openEditDialog(row) {
      this.currentPermission = row
        ? { ...row }
        : {
          permissionName: '',
          code: '',
          isActive: true,
          createTime: '',
          updateTime: ''
        };
      this.isEdit = !!row;
      this.dialogVisible = true;
    },
    // 关闭对话框
    closeDialog() {
      this.dialogVisible = false;
      // 延迟清空数据，确保动画和异步操作完成
      setTimeout(() => {
        this.currentPermission = null;
      }, 300); // 与对话框动画时间一致（默认300ms）
    }
  }
});